import templates from '../../template/index/index'
import fication from '../../template/fication/fication'
import supmember from '../../template/supmember/supmember'
import shopcart from '../../template/shopcart/shopcart'
import personal from '../../template/personal/personal'
const tool = require('../../config/tool.js');
//微信登录  获取购物车底部总数  引用api首页 
import { setLogin, getCartNum, getIndexShow, setAddCart, storeId, getstOrder, getPhone } from '../../config/https'
//购物车列表 删除 修改数量 结算验证 优惠券 超级会员数据说明 数据列表 个人信息 分类数据，
import {
  getCartList,
  setCartRemove,
  setUpNum,
  setCarSubmit,
  getDiscountList,
  getSuperList,
  getSuperData,
  getMyMine,
  category,
  categorygoods
} from '../../config/https'
var WxParse = require('../../wxParse/wxParse.js');
import Dialog from '../../miniprogram_npm/_vant-weapp@0.5.7@vant-weapp/dialog/dialog';
import Toast from '../../miniprogram_npm/_vant-weapp@0.5.7@vant-weapp/toast/toast';
const app = getApp()

Page({
  data: {
    StatusBar: app.globalData.StatusBar,  //状态栏高度
    CustomBar: app.globalData.CustomBar,  //导航栏的高度
    codes: '我是测试',         //测试
    order_animationTo: '',      //假的订单动画
    active_num: 0,              //当前index动画
    showpic: null,       //进入动画
    hidepic: null,       //移除动画
    data_str10: '',      //当前时间，10位时间戳
    onisShon: false,    //升降序
    stastaVip: '',      //0隐藏1显示用于上架
    isIphoneX: '',      //判断是否是不是iphonex
    vipType: 0,        //vip状态1是0不是
    carcount: '',       //购物车合计数
    allNum: 0,          //合计数量
    allPick: 0,         //合计
    alltion: true,     //全选的状态
    shopcar: [],        //购物车数据
    off: true,           //领券中心显示和隐藏
    height: '',         //轮播高度
    scroll: '',         //监听滚动
    shopId: '',        //店铺id
    store_info: '',     //电话和图片
    indexData: [],      //首页数据
    indexgoods: [],     //首页商品列表
    newOrder: [],       //假的订单轮播数据
    show: false,        //首页自提点弹出框
    toaddInfo: false,   //是否地理位置授权成功
    showCon: false,     //顶部的授权提示是否显示
    storesIndex: "0",    //首页自提点的选中下标
    sell_timestart:  '',  //首页预售时间
    sell_timesend: '',   //提货时间
    supList: [],         //超级会员列表数据
    nodes: '',           //超级会员说明
    pagecon: 0,          //超级会员的页数
    load: false,         //加载中提示
    loadAll: false,      //是否已经请求完全部数据
    userData: '',        //用户信息
    status: 1,           //判断是否登录1未登录2登录
    active: 1,           //判断底部的状态1首页
    page: 0,            //分类页数
    pagesize: 7,        //分类每页的返回数
    loadMore: false,    //加载中提示
    finished: false,    //是否已经请求完全部数据
    ficationimg: "",    //分类页大图片
    ficationList: [],   //分类页面接收内容
    mainjgbg: 0,        //分类页面三角
    navindex: 1,        //分类页面 【综合销量价格】默认id
    mainnum: '',        //分享类页面左侧选项 id
    sub_categories: [], //分类页顶部tab项
    tabClassId: 0,      //分类顶部tab列表id
    activeSub: 0,
    mainLeftcont: [],   //分类页左侧选项
    order: "",          //排序名  
    sort: "",           //排序值
    mainindex: '',       //点击首页分类下标
    orderNum: 0,          //配送订单
    orderNumTo: 0,         //自提订单
    orderNumSe: 0,          //物流订单
    orderNumFo:0,           //拼团订单
    classPosi:false,
    nickname:''       //头像是否登录
  },
  imageError(e) { //监听图片是否404
    let index = e.currentTarget.dataset.index;
    let ficationList = this.data.ficationList;
    ficationList[index].thumb = '../../img/noimg.png';
    this.setData({ ficationList })
  },
  // 底部拨打电话
  call_phone(){
    let phone = this.data.store_info.hotline
    wx.makePhoneCall({
      phoneNumber: phone
    })
  },
  //商品分类 -- 左侧栏
  navClick(e) {
    console.log(e)
    let { sub_categories, id } = e.currentTarget.dataset;  
    this.setData({
      mainnum: Number(id),    
      sub_categories,         //右侧栏头部标题
      ficationimg: e.currentTarget.dataset.cateimg,
      navindex: 1,
      mainjgbg: 0,
      page: 0,
      ficationList: [],
      tabClassId: 0,
      onisShon: true,
      order: " ",
      sort: " ",
      activeSub: 0
    })
    //点击调用 分类右边数据
    this.goodsdetailsto()
  },
  theSorting() {    //排序综合、销量数据
    let this_ = this;
    categorygoods({
      page: ++this_.data.page,
      pagesize: this_.data.pagesize,
      order: this_.data.order,
      sort: this_.data.sort,
      sub_cate_id: this_.data.mainnum,
    }).then(res => {
      //console.log("上升,下降")
      this_.setData({ ficationList: res.goods })
    })
  },
  //关闭领券中心
  onOffExpl() {
    this.setData({ off: false })
  },
  navclk(e) {  //点击综合销量价格
    let id = e.currentTarget.dataset.id;
    if (id == 1) { //综合
      this.setData({ mainjgbg: 0, onisShon: true, order: " ", sort: " ", page: 0, finished: false })
      this.theSorting() //排序数据

    } else if (id == 2) {                     //点击销量
      this.setData({ mainjgbg: 0, onisShon: true, order: " sales", sort: " desc", page: 0, finished: false })
      this.theSorting() //排序数据

    } else if (id == 3) { //点击价格的时候
      let onisShon = this.data.onisShon;
      if (onisShon == true) { //升序
        this.setData({ mainjgbg: 1, order: " marketprice", sort: " asc", onisShon: false, page: 0, finished: false })
        this.theSorting()

      } else if (onisShon == false) { //降序
        this.setData({ mainjgbg: 2, order: " marketprice", sort: " desc", onisShon: true, page: 0, finished: false })
        this.theSorting()
      }
    }
    this.setData({ navindex: id })
  },
  
  //授权位置
  setAddinfo() {
    console.log(222)
    //不允许打开定位
    wx.getSetting({
      success: (res) => {
        if (!res.authSetting['scope.userLocation']) {
          //打开提示框，提示前往设置页面
          this.setData({
            showCon: true,
          })
        }
      }
    })
  },

  isnot() {  //第一次进入分销中心
    wx.navigateTo({
      url: '/pages/Districenter/Districenter',
    })
  },
  one(callback) {
    category({ //页面加载动态获取分类列表默认第一项下标id
    }).then(res => {
      if (res.categories.length > 0) {
        this.setData({ mainnum: res.categories[0].id, mainnumTo: res.categories[0].id })
        if (this.data.mainnum){
          callback()
        }     
      }
    })
    
  },
  // getOrder
  order_animation(){   //获取假的订单信息
    const _this = this
    let animation = wx.createAnimation({});
    getstOrder({
    }).then(res => {
      console.log(res)
      this.setData({ newOrder: res.orders })
    })
    clearInterval(_this.data.order_animationTo)
    _this.setData({
      active_num: 0
    })
    var order_animationTo = setInterval(function () {
      _this.setData({
        active_num: _this.data.active_num + 1
      })
      if(_this.data.newOrder.length - 1 == _this.data.active_num){
        _this.setData({
          active_num: 0
        })
      }
      animation
        .opacity(1).top('0rpx').step({
          duration: 1500,
        })
        .opacity(0).top('-10rpx').step({
          duration: 1500,
          delay: 2000
        })

      _this.setData({
        showpic: animation.export()
      })
      animation
        .opacity(0).top('150rpx').step({
          duration: 10
        })
      _this.setData({
        hidepic: animation.export()
      })
    }, 7000)
    _this.setData({
      order_animationTo
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //获取最新时间
    clearInterval(this.time);
    this.time = setInterval(() => {
      //当前时间，10位时间戳
      this.setData({ data_str10: Math.round(new Date() / 1000) })
    }, 1000);
    this.setData({ allPick: 0, allNum: 0})
    if (options.userid) { //通过分享进入页面 得到分享的主人id 
     // Toast("通过分享进入的小程序" + options.userid)
      wx.setStorage({
        key: 'userid',
        data: options.userid,
      })

    } else if (options.scene) { //通过二维码进入页面 得到二维码的主人id  
      //Toast("通过二维码进入的小程序" + decodeURIComponent(options.scene))
      wx.setStorage({
        key: 'userid',
        data: decodeURIComponent(options.scene)
      })

    } else {
      wx.setStorage({
        key: 'userid',
        data: '',
      })
    }
    if (options.active != undefined){
      if (options.active == 3) {
        wx.setNavigationBarTitle({
          title: '超级会员'
        })
        this.setData({ active: Number(options.active) })
        this.indexShow() //地理位置授权
      } else if (options.active ==4){
        this.setData({ active: Number(options.active) })
        this.onorder()
      }
    }
    let that = this
    if (options.codes) {
      this.setData({
        codes: options.codes
      })
    }
  
    this.login() 
    getDiscountList({ //优惠券接口 
    }).then(res=>{
      console.log(res.code)
      if(res.code == 200){
        if (res.list.length==0){
          this.setData({off:false})
        }else{
          this.setData({ off: true })
        }
      }
    })
  },
  login(){
    let that=this;
    const userInfo = wx.getStorageSync("authKey");
    wx.login({
      success(res) {
        var code = res.code
        setLogin({
          code: code,
        }).then(res => {
        //  console.log(res)
          app.globalData.stastaVip = res.version
          app.globalData.userInfo = res.auth_key
          that.setData({ stastaVip: res.version })
          wx.setStorage({
            key: 'authKey',
            data: res.auth_key,
          })
          wx.setStorage({
            key: 'userInfo',
            data: res.userid,
          })
        }).catch(res => {
          console.log(res)
        })
      }
    })
    
    that.setData({ nickname: wx.getStorageSync("nickname")})
    if (this.data.nickname == '') {
      wx.hideShareMenu();   //隐藏右上角转发按钮
    } else {
      wx.showShareMenu()  //显示右上角转发按钮
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var that = this
    if (that.data.active == 1) {
      that.setData({
        stastaVip: app.globalData.stastaVip
      })
      that.indexShow();
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.login(); 
    this.onUserData();
    this.pageLoading = !1;
    var that = this
    let isIphoneX = app.globalData.isIphoneX;
    that.setData({
      isIphoneX: isIphoneX,
      storesIndex: app.globalData.storesIndex,
     
    })

    that.onCartNum()

    if (that.data.active == 5) {
      that.onUserData()
    }
  },
  //首页
  onIndex() {
    this.setData({
      active: '1',
      navindex: 1,
      mainnum: this.data.mainnumTo,
      mainjgbg: 0,
      onisShon: true,
      page: 0,
      allPick: 0,
      allNum:0,
      ficationList: [],
    })
    wx.setNavigationBarTitle({
      title: '首页'
    })
    wx.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#ffffff',
    })
    // this.indexShow()
    this.teturnTop()
    this.indexShow()

    if (this.data.nickname != '') {
      wx.showShareMenu()  //显示右上角转发按钮
    } 
    
  },
  //分类
  oncollection() {
    this.setData({
      active: '2',
      allNum: 0,
      allPick: 0
    })
    wx.setNavigationBarTitle({
      title: '分类'
    })
    wx.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#ffffff',
    })
    wx.hideShareMenu()   //隐藏右上角转发按钮
    this.one(() => {
      this.goodsdetails() //分类页面左边一级的数据
      this.goodsdetailsto()//分类页右边二级数据
    })
  },
  //超级会员
  onsupply() {
    this.setData({
      active: '3',
      mainnum: this.data.mainnumTo,
      mainjgbg: 0,
      onisShon: true,
      navindex: 1,
      page: 0,
      ficationList: [],
      pagecon: 0,
      allPick: 0,
      allNum: 0,
      nickname: wx.getStorageSync("nickname"),
      supList: []
    })
    wx.setNavigationBarTitle({
      title: '超级会员'
    })
    wx.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#ffffff',
    })
    //返回顶部
    this.teturnTop()
    //超级会员说明
    this.showSuper();
    //超级会员列表
    this.showSuperList()

    if (this.data.nickname != '') {
      wx.showShareMenu()  //显示右上角转发按钮
    } 
  },
  //购物车
  onorder() {
    this.setData({
      active: '4',
      mainnum: this.data.mainnumTo,
      navindex: 1,
      mainjgbg: 0,
      onisShon: true,
      page: 0,
      allPick: 0,
      allNum: 0,
      ficationList: [],
    })
    wx.setNavigationBarTitle({
      title: '购物车'
    })
    wx.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#ffffff',
    })
    //从首页的本地读取vip状态
    var that = this
    that.setData({
      alltion: true
    })

    wx.getStorage({
      key: 'vipStast',
      success: function (res) {
        that.setData({
          vipType: res.data
        })
      },
    })
    //返回顶部
    this.teturnTop()
    //获取购物车列表
    this.onCarList()
    wx.hideShareMenu()   //隐藏右上角转发按钮
  },
  navget(e) {
    let id = e.currentTarget.dataset.id;
    let pageto = e.currentTarget.dataset.inpage;
    if(pageto == 1){
      wx.navigateTo({
        url: '/pages/Directsellingto/Directsellingto?id=' + id,
      })
    }else{
      wx.navigateTo({
        url: '/pages/common_page/common_page?id=' + id,
      })
    }
    
  },
  //我的
  onmy() {
    this.setData({
      active: '5',
      mainnum: this.data.mainnum,
      navindex: 1,
      mainjgbg: 0,
      onisShon: true,
      page: 0,
      allPick: 0,
      allNum: 0,
      ficationList: [],
    })
    wx.setNavigationBarTitle({
      title: '我的'
    })
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#FF3C34',
    })
    this.onUserData()
    wx.hideShareMenu()   //隐藏右上角转发按钮
  },
  // 获取个人信息
  onUserData() {
    getMyMine({
    }).then(res => {
      wx.setStorage({
        key: 'nickname',
        data: res.member.nickname,
      })
      if (!res.member.nickname) {
        this.setData({ status: 1 })
      } else {
        this.setData({ status: 2 })
      }
      if (res.level.id == 0) {
        var vipType = 0
      } else {
        var vipType = 1
      }
      this.setData({
        userData: res,
        orderNum: res.total.delivery_total,
        orderNumTo: res.total.self_lifting_total,
        orderNumSe: res.total.logistics_total,
        orderNumFo: res.total.group_total,
        nickname:res.member.nickname,
        vipType
      })
      wx.stopPullDownRefresh() //停止当前页面下拉刷新
    }).catch(err => {
      wx.stopPullDownRefresh() //停止当前页面下拉刷新
    })
  },
  // 跳转普通商品详情
  onDetail(e) {
    const { id, index } = e.currentTarget.dataset;
    if (Number(id)!=''){
      wx.navigateTo({
        url: '/pages/Directsellingto/Directsellingto?id=' + Number(id),
      })
    }
  },

  //大礼包
  onDetails(e) {
    const { id, index, vip } = e.currentTarget.dataset;
    let supList = this.data.supList;
    supList[index].pageview++
    this.setData({ supList })
    wx.navigateTo({
      url: '/pages/Directsellingto/Directsellingto?id=' + id + '&vip=' + vip,
    })
  },
  //跳转团购商品详情
  onDatilsPur(e) {
    const { id } = e.currentTarget.dataset;
    wx.navigateTo({
      url: '/pages/directbuyingto/directbuyingto?id=' + id,
    })
  },
  //  --------------------- active 1 首页 -------------------------
  // 首页数据加载
  indexShow() {
    var that = this
    wx.showLoading({
      title: '加载中...',
    })
    that.order_animation()   //假的订单动画
    //微信授权地理位置
    wx.getLocation({
      type: 'wgs84',
      //用户成功授权
      success: function (res) {
        if (that.data.active==3){
          that.showSuperList() //超级会员列表
          that.showSuper() //超级会员背景数据
        }
        
        app.globalData.lng = res.longitude
        app.globalData.lat = res.latitude
        // console.log("当前位置", res)
        that.setData({
          toaddInfo: true
        })
      },
      fail(res) {
        that.setData({
          toaddInfo: false
        })

      },
      complete(res) {
        getIndexShow({
          lat: app.globalData.lat,
          lng: app.globalData.lng
        }).then(resda => {
          let list = resda.recommend_categories_goods
          let shopId = resda.shop.uniacid   // 店铺id
          app.globalData.storeId = shopId
          wx.setStorageSync('store_id', shopId)
          for(let i = 0; i < list.length; i++){
            let timestart = Number(list[i].presell_timestart)
            let timesend = Number(list[i].presell_sendstatrttime)
            list[i].presell_timestart = tool.tenTimeStr(timestart)
            list[i].presell_sendstatrttime = tool.tenTimeStr(timesend)
            //是否预售1是,0否,如果为1则把当前预售开始时间赋给它
            Number(list[i].is_presell) == 1 ? list[i].is_presell = timestart : list[i].is_presell = false
          }    
          
          if (JSON.stringify(resda.notices) == "[]") {
            resda.notices = false
          }
          wx.setStorage({
            key: 'vipStast',
            data: resda.member_is_vip,
          })
          console.log(resda.store_info)
          that.setData({
            indexData: resda,
            indexgoods: resda.recommend_categories_goods,
            shopId,
            store_info: resda.store_info
          })
          
          console.log(app.globalData)
          wx.hideLoading()
          wx.stopPullDownRefresh()
        }).catch(err => {
          wx.hideLoading()
          wx.stopPullDownRefresh()
        })
      }
    })
  },

  //加入购物车
  onAddCar(e) {
    var that = this
    let { id, opid } = e.currentTarget.dataset
    setAddCart({
      total: 1,
      optionid: opid,
      id: id
    }).then(res => {
      that.setData({
        carcount: res.cartcount
      })
      Toast("添加购物车成功")
    }).catch(err => {
      if(err.code == 403){
        Toast("添加购物车失败,请先登入~")
      }
    })
  },

  //点击打开其他小程序
  onProcedures(e) {
    let { isself, index, uniacid } = e.currentTarget.dataset
    app.globalData.storesIndex = index
    wx.setStorageSync('store_id', uniacid)
    // indexData, storesIndex: index,
    this.setData({  show: false })
    this.index_data(uniacid)
  },
  index_data(shopId){
    console.log('重新获取首页的数据')
    var that = this
    getIndexShow({ 
      lat: app.globalData.lat,
      lng: app.globalData.lng
    }).then(resda => {
      let list = resda.recommend_categories_goods
      let carcount = ''
      app.globalData.storeId = shopId
      for (let i = 0; i < list.length; i++) {
        let timestart = Number(list[i].presell_timestart)
        let timesend = Number(list[i].presell_sendstatrttime)
        list[i].presell_timestart = tool.tenTimeStr(timestart)
        list[i].presell_sendstatrttime = tool.tenTimeStr(timesend)
        carcount += Number(list[i].cart_num) 
      }
      console.log(carcount)
      wx.setStorageSync('store_id', shopId)
      that.setData({
        indexData: resda,
        indexgoods: resda.recommend_categories_goods,
        shopId,
        carcount
      })
    }).catch(err => {
      console.log(err)
    })
  },
  
  //跳转授权页
  onLogs() {
    wx.navigateTo({
      url: '/pages/logs/logs',
    })
  },
  //位置授权提示框事件
  changeModalCancel(e) {
    let sure = e.currentTarget.dataset.name
    this.setData({
      showCon: false
    })
  
    if (sure == "delo") {
      this.setData({ toaddInfo: true })
    } 
  },
  //自提点弹出层显示
  onPopAdd() {
    if (this.data.indexData.stores.length > 0) {
      let show = !this.data.show
      this.setData({
        show
      })
    } else {
      Toast("其他门店正在申请中~~")
      return
    }
  },
  // 返回顶部
  teturnTop() {
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },
  // 监听滚动事件   scrollTop 滚动的距离
  onPageScroll: function (e) {
    this.setData({
      scroll: e.scrollTop
    })
  },
  //获取轮播高度
  imgHeight: function (e) {
    var winWid = wx.getSystemInfoSync().windowWidth; //获取当前屏幕的宽度
    var imgh = e.detail.height; //图片高度
    var imgw = e.detail.width; //图片宽度
    var swiperH = winWid * imgh / imgw + "px"
    this.setData({
      height: swiperH //设置高度
    })
  },
  // ----------------------- 2分类 --------------------
  onClick(e) {
    let index = e.detail.index; //当前点击下标
    let id = this.data.sub_categories[index].id; //当前点击此项tab栏id
    this.setData({ tabClassId: id })
    categorygoods({
      page: 1,
      pagesize: this.data.pagesize,
      cate_id: this.data.mainnum,             //一级分类id
      sub_cate_id: id,     //二级分类id
      order: '',             //排序名 综合可不填， 销量 sales， 价格 marketprice
      sort: ''                //排序值 综合可不填 销量 desc ， 价格  asc(升序) desc（降序）
    }).then(res => {
      console.log(res)
      // if (res.total_num <= this.data.pagesize) {
      //   this.setData({ finished: true })
      // }
      this.setData({ ficationList: res.goods })
    })
  },
  onmodaa(e) {
    let this_ = this;
    let id = e.currentTarget.dataset.id;
    this_.setData({ mainnum: id, active: "2" })
    category({
    }).then(res => {
      for (let i in res.categories) {
        if (Number(res.categories[i].id) == id) {
          this_.goodsdetailsto();
          this_.setData({ sub_categories: res.categories[i].sub_categories })
        }
      }
      this_.setData({
        mainLeftcont: res.categories,
      })
    })
  },
  //点击首页分类
  onmod(e) {
    let this_ = this;
    let { index, id } = e.currentTarget.dataset;
    this_.setData({ mainnum: id, mainindex: index })
    category({
    }).then(res => {
      this_.setData({ sub_categories: res.categories[index].sub_categories })
    })
  },
  //分类左边
  goodsdetails() {
    let this_ = this;
    let index = this_.data.mainindex
    category({
    }).then(res => {
      console.log(this_.data.mainnum +'=='+ this_.data.mainnumTo)
      if (this_.data.mainnum == this_.data.mainnumTo) {
        this_.setData({ sub_categories: res.categories[0].sub_categories })
      } else {
        this_.setData({ sub_categories: res.categories[index ? index : 0].sub_categories })
      }
      this_.setData({
        mainLeftcont: res.categories,
        vipType: res.member_is_vip
        
      })
    })
  },

  //二级数据 分类右边
  goodsdetailsto() {
    var that = this;
    wx.showLoading({//加载提示动画
      title: '数据加载中...',
    })
    console.log('id+=',that.data.mainnum)
    categorygoods({
      page: ++that.data.page,
      pagesize: that.data.pagesize,
      cate_id: that.data.mainnum,             //一级分类id
      sub_cate_id: that.data.tabClassId,     //二级分类id
      order: that.data.order,             //排序名 综合可不填， 销量 sales， 价格 marketprice
      sort: that.data.sort                //排序值 综合可不填 销量 desc ， 价格  asc(升序) desc（降序）
    }).then(res => {
      console.log(res)
      wx.hideLoading() //加载提示动画消失
      var ficationList = that.data.ficationList;
      ficationList = ficationList.concat(res.goods)
      this.setData({ ficationList, vipType:res.member_is_vip  })
      if (ficationList.length == 0) {
      } else {
        that.setData({
          finished: res.goods.length < that.data.pagesize ? true : false
        })
      }
      wx.stopPullDownRefresh();
    }).catch(err => {
      wx.hideLoading() //加载提示动画消失
    })
  },
  //分类加入购物车或者减少
  onFicationNum(index, dataset, num, ficationList) {
    if (Number(num) < 1) {
      num = 0
    } else if (Number(num) > Number(ficationList[index].total)) {
      num = Number(ficationList[index].total)

    }
    ficationList[index].cart_num = num
    setUpNum({
      optionid: ficationList[index].optionid,
      goods_id: ficationList[index].id,
      total: ficationList[index].cart_num
    }).then(res => {
      this.setData({
        ficationList,
        carcount: res.cartcount
      })
    })
  },
  // 商品加入购物车或移除
  onShopNum(e) {
    var e = e
    let ficationList = this.data.ficationList;
    let current_time = this.data.data_str10;  //当前时间
    let { index, dataset, activitystart, activityend, inpage } = e.currentTarget.dataset; //当前列表index
    let num = ficationList[index].cart_num; //num++
    if (inpage == 1){
      if (activitystart > current_time) {
        Toast("当前商品还未开售~~")
        return
      }
      if (activityend < current_time) {
        Toast("当前活动已结束，请下次再来~~")
        return
      }
    }
    if (ficationList[index].stock == 0) {
      Toast("当前商品库存不足~~")
      return
    }
    if (num == 0) {
      //加入购物车
      this.onAddCar(e);
      ++ficationList[index].cart_num; //num++
    } else {
      // 购物车加减
      if (dataset == 'true') {
        num--
      } else {
        if (num == ficationList[index].stock) {
          Toast("不能超过最大购买数!!!")
          return
        } else if (num == ficationList[index].usermaxbuy){
          Toast("此商品限购" + ficationList[index].usermaxbuy+"件")
          return
        }else{
          num++
        }
        
      }
      this.onFicationNum(index, dataset, num, ficationList);
    }
    this.setData({
      ficationList
    })
  },
  // 首页商品加入购物车或移除
  indexgoodsLis(e) {
    console.log('加入')
    var e = e
    let goodsList = this.data.indexgoods;
    let { index, dataset } = e.currentTarget.dataset; //当前列表index、状态
    let num = goodsList[index].cart_num; //num++
    if (goodsList[index].total == 0) {
      Toast("当前商品库存不足~~")
      return
    }
    if (num == 0) {
      //加入购物车
      this.onAddCar(e);
      ++goodsList[index].cart_num; //num++
    } else {
      // 购物车加减
      if (dataset == 'true') {
        num--
      } else {
        console.log(num + '===' + goodsList[index].usermaxbuy)
        if (num == goodsList[index].total) {
          Toast("不能超过最大购买数!!!")
          return
        } else if (num == goodsList[index].usermaxbuy) {
          Toast("此商品限购" + goodsList[index].usermaxbuy + "件")
          return
        } else {
          num++
        }

      }
    }
    setUpNum({
      optionid: goodsList[index].optionid,
      goods_id: goodsList[index].id,
      total: goodsList[index].cart_num
    }).then(res => {
      this.setData({
        carcount: res.cartcount
      })
    })
    this.setData({
      indexgoods: goodsList
    })
  },
  // 首页input输入框
  index_input(event){
    var event = event
    var active = this.data.active; //当前页面
    var newNum = event.detail.value //输入框里的值
    console.log(newNum)
    var index = event.currentTarget.dataset.index //当前改变的产品下标
    var goodsList = this.data.indexgoods //首页的商品数据
    if (Number(newNum) > Number(goodsList[index].total)) {
      newNum = Number(goodsList[index].total)
      Toast('该商品数量有限~');
    } else if (Number(newNum) > Number(goodsList[index].usermaxbuy)) {
      newNum = Number(goodsList[index].usermaxbuy)
      Toast('该商品限购，不能超过限购数量~');
    }
    setUpNum({
      optionid: goodsList[index].optionid,
      goods_id: goodsList[index].id,
      total: newNum
    }).then(res => {
      this.setData({
        carcount: res.cartcount
      })
    })
  },
  // -----------------------  3超级会员  --------------------
  // 读取超级会员说明
  showSuper() {
    var that = this
    getSuperList({
    }).then(res => {
      that.setData({ nodes: res })
      WxParse.wxParse('article', 'html', res.description, that, 5);
    })
  },
  //读取超级会员列表
  showSuperList() {
    let that = this
    that.setData({
      load: true,
      supList: []
    })
    getSuperData({
      page: ++that.data.pagecon
    }).then(res => {
      let list = res.list
      list = that.data.supList.concat(list)
      that.setData({
        load: false,
        supList: list
      })
      if (list.length == 0) {
      } else {
        that.setData({
          loadAll: res.list.length < res.pagesize ? true : false
        })
      }
      wx.stopPullDownRefresh();
    })
  },

  // ----------------------- 4购物车 --------------------
  //读取底部购物车数量
  onCartNum() {
    getCartNum({
    }).then(res => {
      if (res.cartcount == null) {
        res.cartcount = 0
      }
      this.setData({
        carcount: res.cartcount
      })
    })
  },
  // 购物车列表数据
  onCarList() {
    getCartList({
    }).then(res => {
      let allPick = this.data.allPick;
      let allNum = this.data.allNum;
      res.list.forEach(item => {
        item.checkbox = true
        if (this.data.vipType == 0) {
          allPick = allPick+(item.marketprice) * (item.total)
        } else {
          allPick = allPick + (item.vipprice) * (item.total)
        }
        allNum = allNum + Number(item.total)
      })
      
      this.setData({
        shopcar: res.list,
        allPick,
        allNum
      })
      wx.stopPullDownRefresh()
    })
  },
  //购物车点击删除
  onCartDel() {
    //数据列表
    let shopcar = this.data.shopcar
    //需要删除的购物车id
    var checArrs = [{}];
    var index = -1;

    Dialog.confirm({
      message: '你要删除当前选中的商品吗~~',
    }).then(() => {
      wx.showLoading({
        title: '删除中...',
      })
      //循环删除
      for (let i = 0; i < shopcar.length; i++) {
        if (shopcar[i].checkbox) {
          index++
          var cartId = shopcar[i].id
          checArrs[index] = cartId
          shopcar.splice(i, 1);
          i--;
        }
      }
      if (JSON.stringify(checArrs) == '[{}]') {
        wx.hideLoading()
        Toast("请选择商品~~")
        return
      }
      var that = this
      setCartRemove({
        ids: checArrs
      }).then(res => {
        Toast("删除成功~~")
        wx.hideLoading()
        that.setData({
          shopcar,
          allPick: 0,
          allNum: 0,
          carcount: res.cartcount == null ? '0' : res.cartcount
        })
      }).catch(err => {
        wx.hideLoading()
        Toast(err.massage)
      })
    }).catch(ree => {
      wx.hideLoading()
    })
  },
  //全选
  onAllChange(event) {
    var shopcar = this.data.shopcar
    var allPick = 0; //总价
    var allNum = 0; //总数量
    //判断是否是全选
    if (event.detail == true) {
      wx.showLoading({
        title: '请稍后...',
      })
      //遍历数组全选
      shopcar.forEach(item => {
        console.log(item)
        item.checkbox = true;
        //价格
        if (this.data.vipType == 0) {
          allPick = allPick + (item.marketprice) * (item.total);
        } else {
          allPick = allPick + (item.vipprice) * (item.total)
        }
        allNum = allNum + Number(item.total)
      })
    } else {
      wx.showLoading({
        title: '请稍后...',
      })
      //遍历数组全选
      shopcar.forEach(item => {
        item.checkbox = false;
      })
    }
    this.setData({
      allNum,
      allPick,
      shopcar,
      alltion: event.detail
    })
    wx.hideLoading()
  },
  //点击选中或者取消
  onChange(event) {
    //全选的框架
    let alltion = this.data.alltion;
    //列表数据数组
    let shopcar = this.data.shopcar;
    // 总数量
    let allNum = Number(this.data.allNum);
    //总价格、
    let allPick = Number(this.data.allPick);
    let index = event.currentTarget.dataset.index;
    shopcar[index].checkbox = event.detail
    //取出当前的价格和数量
    let total = Number(shopcar[index].total)
    if (this.data.vipType == 0) {
      var pick = Number((shopcar[index].marketprice) * total)
    } else {
      var pick = Number((shopcar[index].vipprice) * total)
    }
    //判断如果是选中
    if (event.detail == true) {
      allNum = allNum + total
      allPick = allPick + pick
    } else { //相反
      allNum = allNum - total
      allPick = allPick - pick
    }
    let trueNum = 0
    shopcar.forEach(item => {
      if (item.checkbox == true) {
        trueNum++
      }
    })
    //判断是否全选
    if (trueNum == shopcar.length) {
      alltion = true
    } else {
      alltion = false
    }
    this.setData({
      alltion,
      shopcar,
      allNum,
      allPick
    })
  },

  //点击数量添加或者减少
  onIncrease(e, newNum) {
    console.log(newNum)
    if (!newNum) {
      newNum = 0
    }
    // 总数量
    let allNum = Number(this.data.allNum);
    //总价格、
    let allPick = Number(this.data.allPick);
    //列表数据数组
    let shopcar = this.data.shopcar;
    let index = e.currentTarget.dataset.index;
    //加还是减true减
    let start = e.currentTarget.dataset.start;
    let total = Number(shopcar[index].total)
    if (this.data.vipType == 0) {
      var pick = Number(shopcar[index].marketprice) * total
      var newPick = Number(shopcar[index].marketprice) * (newNum == 0 ? 1 : newNum)
    } else {
      var pick = Number(shopcar[index].vipprice) * total
      var newPick = Number(shopcar[index].vipprice) * (newNum == 0 ? 1 : newNum)
    }
    // shopcar[index].total = Number(shopcar[index].total) + newNum - total
    //判断是加减还是输入
    if (newNum == 0) {
      if (start == 'true') {
        if (total == 1) {
          Toast("不能再减了")
          return
        }
        shopcar[index].total--
      } else {
        if (total == shopcar[index].totalmaxbuy) {
          Toast("不能超过最大购买数!!!")
          return
        }
        shopcar[index].total++
      }
    } else {
      shopcar[index].total = newNum
    }
    //是否选中
    let checkbox = shopcar[index].checkbox
    if (newNum != 0) {
      if (checkbox) {
        allPick = allPick + Number(newPick) - pick;
        allNum = allNum + Number(newNum) - total
      }
    } else if (newNum == 0 && checkbox) {
      if (start == 'true') {
        allPick = allPick - Number(newPick);
        allNum--
      } else {
        allPick = allPick + Number(newPick);
        allNum++
      }
    }
    //修改购物车数量
    setUpNum({
      goods_id: shopcar[index].goodsid,
      optionid: shopcar[index].optionid,
      total: shopcar[index].total
    }).then(res => {
      this.setData({
        carcount: res.cartcount
      })
    })
    this.setData({
      shopcar,
      allPick,
      allNum
    })
  },

  // 监听购物车input输入事件可以分类使用
  newTotoal(event) {
    var event = event
    var active = this.data.active; //当前页面
    //现在的数量
    var newNum = event.detail.value //输入框里的值
    var index = event.currentTarget.dataset.index //当前改变的产品下标
    if (active == 4) {
      var shopcar = this.data.shopcar //购物车数据
    } else if (active == 2) {
      var shopcar = this.data.ficationList //分类页接收的内容
    }
      
    //获取数据列表
    if (newNum < Number(shopcar[index].cart_num)) { 
      event.currentTarget.dataset.start = 'true' //减
    } else if (newNum > shopcar[index].cart_num) {
      event.currentTarget.dataset.start = 'false' //加  
    }
    
   //cart_num购买的数量 total最大数量 usermaxbuy限购数量
    if (newNum == '' || newNum < 1) { //如果输入的内容为空或者小于1
      newNum = active == 2 ? 0 : 1 //如果是分类页 输入框的值为0 如果是购物车输入框的值为1  
    } else if (Number(shopcar[index].usermaxbuy)==0){ 
      if (Number(newNum) > Number(shopcar[index].total)) {
        newNum = Number(shopcar[index].total)
      } 
    } else if (shopcar[index].usermaxbuy != ''){
      if (Number(newNum) > Number(shopcar[index].usermaxbuy)) {
        newNum = Number(shopcar[index].usermaxbuy)
      } 
    }
    //输入框的值  大于    分类页 Number(shopcar[index].total)  购物车 Number(shopcar[index].totalmaxbuy)
    //输入框的值    分类页 Number(shopcar[index].total)   Number(shopcar[index].totalmaxbuy)
    //判断是购物车还是分类
    if (active == 4) {
       this.onIncrease(event, newNum)
    } else if (active == 2) {
      this.onFicationNum(index, event.currentTarget.dataset.start, newNum, shopcar)
    }
  },
  // 结算验证
  onSubmit() {
    var that = this;
    var cartArrs = [];  //商品id
    var optionid = [];  //规格id
    var numArrs = [];    //数量
    var cartId = [];    //唯一id用于删除
    var vipprice = 0; //会员价
    that.data.shopcar.forEach((item, index) => {
      if (item.checkbox) {
        vipprice = vipprice + (item.vipprice * item.total)
        cartArrs.push(item.goodsid);
        optionid.push(item.optionid);
        numArrs.push(item.total);
        cartId.push(item.id)
      }
    })
    let nickname = wx.getStorageSync("nickname");
    if (!nickname){
      wx.navigateTo({
        url: '/pages/logs/logs',
      })
    }else if(!this.pageLoading) {
      this.pageLoading = !0;

      if (cartArrs.length < 1) {
        Toast("请选择需要结算的商品")
        this.pageLoading = !this.pageLoading;
        return
      }else{
        setCarSubmit({
          ids: cartId
        }).then(res => {
          console.log(res)
          wx.navigateTo({
            url: '/pages/purorders/purorders?id=' + JSON.stringify(cartArrs) + '&optionid=' + JSON.stringify(optionid) + '&total=' + JSON.stringify(numArrs) + '&typeCar=1' + '&cartId=' + JSON.stringify(cartId) + '&vipprice=' + vipprice
          })
        }).catch(err => {
          console.log(err)
          Toast(err.message)
          this.pageLoading = !this.pageLoading;
        })
      }
    }
  },
  member_status(){
    Toast('你已绑定会员卡，无需重新绑定~~')
  },
  getPhoneNumber: function (e) {
    const detail = e.detail;
    const userInfo = wx.getStorageSync("authKey");
    const my_info = this.data.userData
    console.log(my_info)
    if (!userInfo) {
      wx.navigateTo({
        url: '/pages/logs/logs',
      })
    }else{
      if (my_info.member.member_status == 1){  //1为已绑定会员卡
        Toast('你已绑定会员卡，无需重新绑定~~')
      }else{
        wx.login({
          success(res) {
            if (res.code) {
              getPhone({
                sessionKey: res.code,
                data: detail.encryptedData,
                iv: detail.iv
              }).then()
            } else {
              console.log('登录失败！' + res.errMsg)
            }
          }
        })
      }
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.setBackgroundColor({
      backgroundColor: '#eeeeee',
    })
    wx.setBackgroundColor({
      backgroundColorTop: '#eeeeee',
    })
    if (this.data.active == 1) {
      this.indexShow()
    } else if (this.data.active == 2) { //---------------------------------------------
      this.setData({
        navindex: 1,
        mainnum: this.data.mainnumTo,
        mainjgbg: 0,
        onisShon: true,
        page: 0,
        ficationList: [],
        order: " ",
        sort: " "
      })
       this.goodsdetails() //分类页面左边一级的数据
       this.goodsdetailsto()//分类页右边二级数据
      wx.stopPullDownRefresh()
    } else if (this.data.active == 3) {
      this.setData({ pagecon: 0 })
      //超级会员说明
      this.showSuper();
      //超级会员列表
      this.showSuperList()
      wx.stopPullDownRefresh()
    } else if (this.data.active == 4) {
      this.setData({allPick: 0,allNum: 0})
      this.onCarList();
    } else if (this.data.active == 5) {
      this.onUserData()
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (!this.data.finished && !this.data.loadMore && this.data.active == 2) {
      this.goodsdetailsto()
    } else if (!this.data.load && !this.data.loadAll && this.data.active == 3) {
      this.showSuperList()
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    if (this.data.active == 1) {
      return {
        title: '满足顾客需求，创造精彩生活 小伙伴们都在这里快来瞅瞅哟~',
        path: '/pages/tapswitching/tapswitching?active=1' + '&userid=' + wx.getStorageSync('userInfo'),
        imageUrl: this.data.indexData.advs[0].thumb,  //转发图片 默认当前页面图片
        success: (res) => {//转发成功
        }
      }
    }else if (this.data.active == 3) {
        return {
          title: '满足顾客需求，创造精彩生活 超级会员，特权独享',
          path: '/pages/tapswitching/tapswitching?active=3' + '&userid=' + wx.getStorageSync('userInfo'),
          imageUrl: this.data.nodes.headimg,  //转发图片 默认当前页面图片
        }
     }
  },
  logbut(){
    wx.navigateTo({
      url: '/pages/logs/logs',
    })
  }
})